import { cloneDeep } from "lodash";
import { useUserState } from "@/store/useUserState";
import type { RouteRecordRaw } from "vue-router";

type routeMapType = {
  title: string;
  key: string;
  children: Array<routeMapType>;
};
// 根据动态路由生成路由树
function getRouteTree(childrenList: any, list: any[]) {
  if (!childrenList) return;
  for (let i = 0; i < childrenList.length; i++) {
    const item = childrenList[i];
    if (item.meta?.nameCn) {
      const routeMap: routeMapType = {
        title: item.meta?.nameCn,
        key: item.name,
        children: [],
      };
      if (item.children && item.children.length)
        getRouteTree(item.children, routeMap.children);

      if (item.meta?.btnKey && item.meta?.btnKey.length) {
        const list= item.meta?.btnKey;
        for (let j = 0; j < list.length; j++) {
          const btnMap = {
            title: list[j].nameCn,
            key: list[j].value,
            type: "btn",
          };
          routeMap.children.push(btnMap);
        }
      }
      list.push(routeMap);
    }
  }
  return list;
}
// 获取权限路由 并处理二级路由重定向无路由情况
function getAsyncRoute(
  childrenRoutes: Array<RouteRecordRaw>,
  permissionKeys: string[],
  list: Array<RouteRecordRaw>
) {
  for (let i = 0; i < childrenRoutes.length; i++) {
    const item = childrenRoutes[i];
    const name = item.name as string;
    if (
      item.path === "/" ||
      (permissionKeys.includes(name) && item.children && item.children.length)
    ) {
      const cloneData = cloneDeep(item);
      const redirectPath = handleRedirectNoPermission(cloneData);
      if (redirectPath) {
        cloneData.redirect = redirectPath;
      }
      cloneData.children = [];
      list.push(cloneData);
      getAsyncRoute(item.children, permissionKeys, cloneData.children);
    } else if (
      permissionKeys.includes(name) &&
      (!item.children || !item.children?.length)
    ) {
      list.push(item);
    }
  }
}

// 重定向
function handleRedirectNoPermission(route: RouteRecordRaw) {
  const { userRoleInfo } = useUserState();
  const permission = userRoleInfo?.permission;
  if (!permission) return "";
  const keysList = JSON.parse(permission);
  let pathStr = "";

  const { name, children = [] } = route;
  if (keysList.includes(name)) {
    for (let i = 0; i < children.length; i++) {
      const item = children[i];
      if (keysList.includes(item.name)) {
        pathStr = "/" + name + "/" + item.name;
        break;
      }
    }
  }
  return pathStr;
}


// 权限改变
const onChangeCurrentPermission = () => {
  const { getUserRoleData } = useUserState();
  const { userInfo } = LocalCache.getCache("user", true);
  getUserRoleData(userInfo.id);
};

export {
  getRouteTree,
  getAsyncRoute,
  handleRedirectNoPermission,
  onChangeCurrentPermission,
};
